package com.changgou.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.entity.Result;
import com.changgou.goods.feign.SkuFeign;
import com.changgou.goods.pojo.Sku;
import com.changgou.search.dao.EsManagerMapper;
import com.changgou.search.pojo.SkuInfo;
import com.changgou.search.service.EsManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class EsManagerServiceImpl implements EsManagerService {

    @Autowired
    private SkuFeign skuFeign;

    @Autowired
    private ElasticsearchTemplate esTemplate;

    @Autowired
    private EsManagerMapper esManagerMapper;

    @Override
    public void createIndexAndMapping() {
        //创建索引
        esTemplate.createIndex(SkuInfo.class);
        //创建映射
        esTemplate.putMapping(SkuInfo.class);
    }

    @Override
    public void importAll() {
        Result result = skuFeign.findSkuListBySpuId("all");
        List<Sku> skuList = (List<Sku>) result.getData();
        if(skuList != null && skuList.size() > 0){
            //ES存入数据,json格式
            //将skuList转换为json
            String json = JSON.toJSONString(skuList);
            List<SkuInfo> skuInfos = JSON.parseArray(json, SkuInfo.class);
            for (SkuInfo skuInfo : skuInfos) {
                //将spec规格的字符串,转换为Map对象
                Map map = JSON.parseObject(skuInfo.getSpec(), Map.class);
                skuInfo.setSpecMap(map);
            }
            esManagerMapper.saveAll(skuInfos);
        }else{
            throw new RuntimeException("当前没有数据,无法导入到索引库中");
        }
    }


    @Override
    public void importDataToEsBySpuId(String spuId) {
        Result result = skuFeign.findSkuListBySpuId(spuId);
        List<Sku> skuList = (List<Sku>) result.getData();
        //将skuList转换为List<SkuInfo>
        if(skuList.size()<=0 || skuList == null){
            throw new RuntimeException("当前没有数据,无法导入到索引库中");
        }
        String json = JSON.toJSONString(skuList);
        //转换成skuInfo
        List<SkuInfo> skuInfos = JSON.parseArray(json, SkuInfo.class);
        for (SkuInfo skuInfo : skuInfos) {
            //将spec规格的字符串,转换为Map对象
            Map map = JSON.parseObject(skuInfo.getSpec(), Map.class);
            skuInfo.setSpecMap(map);
        }
        esManagerMapper.saveAll(skuInfos);
    }

    @Override
    public void delDataBySpuId(String spuId) {
        //根据spuId获取要删除的sku列表
        Result result = skuFeign.findSkuListBySpuId(spuId);
        List<Sku> skuList = (List<Sku>) result.getData();
        if(skuList.size()<=0 || skuList == null){
            throw new RuntimeException("当前没有数据,无法从索引库中删除");
        }
        for (Sku sku : skuList) {
            esManagerMapper.deleteById(Long.parseLong(sku.getId()));
        }
    }
}
